<template>
  <div class="dictionary-wrapper">
    <!-- 主要部分 -->
    <main class="user_main_part">
      <!-- 💭筛选框和按钮 -->
      <section class="search_part">
        <el-row style="width: 90%; margin: 0 auto">
          <el-col :span="6">
            <el-input
              style="width: 70%"
              size="mini"
              placeholder="请输入字典名称"
              v-model="dictName"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" size="mini" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button size="mini" icon="el-icon-refresh" @click="handleReset">重置</el-button>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>
      </section>
      <!-- 💭表格部分 -->
      <section
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
        :stripe="true"
        class="tabel_part"
      >
        <el-table
          :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
          :stripe="true"
          row-key="id"
          size="mini"
          :data="tableData"
        >
          <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
          <el-table-column label="字典名称" align="center" prop="dictName">
            <template v-slot="{ row }">
              <span style="color: blue; cursor: pointer" @click="handleSkipDetail(row)">
                {{ row.dictName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="字典编号" align="center" prop="dictCode"> </el-table-column>
          <el-table-column label="状态" align="center" prop="isStatus">
            <template v-slot="{ row }">
              <span> {{ stateEnums[row.isStatus] }} </span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark"></el-table-column>
          <el-table-column label="操作" align="center" min-width="120px">
            <template v-slot="{ row }">
              <el-button icon="el-icon-edit" size="mini" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" @click="handleDelete(row)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="height: 60px" align="middle">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageParams.pageNo"
            :page-sizes="[10, 20, 50]"
            :page-size="pageParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </section>
      <!-- 弹窗 -->
      <el-dialog :visible="diaVis" :title="diaTitle" @close="handleCancel" width="500px">
        <el-form :model="formData" :rules="formRules" ref="formRef">
          <el-form-item
            v-for="item in formColumns"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            label-width="100px"
          >
            <el-input
              v-if="item.ele === 'input'"
              v-model="formData[item.prop]"
              style="width: 80%"
              :disabled="item.disabled"
              size="mini"
            ></el-input>
            <el-radio-group v-if="item.ele === 'radio'" v-model="formData[item.prop]" :disabled="item.disabled">
              <el-radio v-for="it in item.radios" :key="it.value" :label="it.value">{{ it.label }}</el-radio>
            </el-radio-group>
            <el-input
              v-if="item.ele === 'textarea'"
              v-model="formData[item.prop]"
              type="textarea"
              style="width: 80%"
              :disabled="item.disabled"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="handleConfirm">确认</el-button>
          <el-button size="mini" @click="handleCancel">取消</el-button>
        </span>
      </el-dialog>
    </main>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  data() {
    return {
      dictName: '',
      tableData: [],
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      formColumns: [
        { ele: 'input', label: '字典名称：', prop: 'dictName', disabled: false },
        { ele: 'input', label: '字典编号：', prop: 'dictCode', disabled: false },
        {
          ele: 'radio',
          label: '状态：',
          prop: 'isStatus',
          radios: [
            { label: '正常', value: '0' },
            { label: '失效', value: '1' },
          ],
          disabled: false,
        },
        { ele: 'textarea', label: '备注：', prop: 'remark', disabled: false },
      ],
      formData: {
        dictName: '',
        dictCode: '',
        isStatus: '',
        remark: '',
      },
      formRules: {
        dictName: [{ required: true, message: '请输入', trigger: 'blur' }],
        dictCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        isStatus: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      diaTitle: '',
      diaVis: false,
      diaIsAdd: true,
      stateEnums: {
        0: '正常',
        1: '失效',
      },
      updateId: '',
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    ...mapActions('dictionaryManage', ['getDicDataAPI', 'deleteDicDataAPI', 'createDicDataAPI', 'editDicDataAPI']),

    // 点击搜索
    handleSearch() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.getTableData()
    },

    // 获取表格数据
    getTableData() {
      const params = {
        dictName: this.dictName,
        ...this.pageParams,
      }
      this.getDicDataAPI({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.total = data.total
          this.pageParams.pageNo = data.current
          this.tableData = data.records
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    handleAdd() {
      this.diaTitle = '添加字典'
      this.formColumns[1].disabled = false
      this.diaIsAdd = true
      this.diaVis = true
    },
    handleReset() {
      this.dictName = ''
      this.total = 0
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.getTableData()
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 用户点击了确定按钮，执行相应的操作
          const params = {
            id: row.id,
          }
          this.deleteDicDataAPI({ params }).then(res => {
            const { code, message } = res
            if (code === 200) {
              this.$message.success('删除成功')
              const pageLastOne =
                this.total % this.pageParams.pageSize === 1 &&
                Math.floor(this.total / this.pageParams.pageSize) === this.pageParams.pageNo - 1
              if (pageLastOne) {
                if (this.pageParams.pageNo !== 1) {
                  this.pageParams.pageNo = this.pageParams.pageNo - 1
                }
              }
              this.getTableData()
            } else {
              this.$message.error(message || '服务异常，请稍后重试!')
            }
          })
        })
        .catch(() => {})
    },
    // 编辑按钮
    handleEdit(row) {
      this.updateId = row.id
      this.diaTitle = '修改字典'
      this.formColumns[1].disabled = true
      this.diaIsAdd = false
      this.formData = { ...row }
      this.diaVis = true
    },
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getTableData()
    },
    // 进入字典详情
    handleSkipDetail(row) {
      this.$router.push({
        path: '/dictionary-item',
        query: {
          dictTypeCode: row.dictTypeCode,
          parentId: row.id,
          name: row.dictName,
        },
      })
    },
    publicClose() {
      this.$refs.formRef.resetFields()
      this.diaVis = false
      this.formData = {
        dictName: '',
        dictCode: '',
        isStatus: '',
        remark: '',
      }
    },
    async handleConfirm() {
      await this.$refs.formRef.validate()
      const data = {
        ...this.formData,
        dictTypeCode: this.formData.dictCode,
      }
      data.parentId = '0'
      if (this.diaIsAdd) {
        this.createDicDataAPI({ data }).then(res => {
          const { code } = res
          if (code === 200) {
            this.$message.success('创建成功')
            this.getTableData()
          }
        })
      } else {
        data.id = this.updateId
        this.editDicDataAPI({ data }).then(res => {
          const { code } = res
          if (code === 200) {
            this.$message.success('修改成功')
            this.getTableData()
          }
        })
      }
      this.publicClose()
    },
    handleCancel() {
      this.publicClose()
    },
  },
}
</script>

<style lang="scss" scoped>
.dictionary-wrapper {
  height: 100%;
  background-color: $white;
  .user_main_part {
    background-color: $white;
    padding: 12px;
    .search_part {
      margin-top: 12px;
    }
    .tabel_part {
      margin-top: 24px;
    }
  }
}
</style>
